/**
 * 手机号登录页面组件
 * 提供手机号验证码登录功能，包括：
 * - 手机号验证
 * - 验证码发送和验证
 * - 响应式布局支持
 */

<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 左侧品牌展示区域 -->
      <div class="login-left">
        <div class="brand">
          <div class="logo">EDU</div>
          <h1>教育共享平台</h1>
          <p class="slogan">让知识触手可及</p>
          <img src="@/assets/PhoneLogin.png" alt="教育平台图片" class="brand-image">
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="login-right">
        <div class="login-header">
          <h2>手机号登录</h2>
          <p>请输入手机号获取验证码登录</p>
        </div>
        <form class="login-form" @submit.prevent="handleLogin">
          <!-- 手机号输入 -->
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="loginForm.mobile" 
                placeholder="请输入手机号"
                @blur="validateMobile"
              >
            </div>
            <span class="error-message" v-if="mobileError">{{ mobileError }}</span>
          </div>

          <!-- 验证码输入 -->
          <div class="form-group">
            <div class="input-group code-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="loginForm.userCode" 
                placeholder="请输入验证码"
              >
              <button 
                type="button" 
                class="code-btn" 
                :disabled="isCountDown || !isMobileValid" 
                @click="sendCode"
              >
                {{ countDownText }}
              </button>
            </div>
            <span class="error-message" v-if="codeError">{{ codeError }}</span>
          </div>

          <!-- 提交按钮 -->
          <div class="form-group">
            <button type="submit" :disabled="loading" class="submit-btn">
              <span class="btn-text">{{ loading ? '登录中...' : '登录' }}</span>
            </button>
          </div>

          <!-- 底部链接 -->
          <div class="bottom-links">
            <div class="auth-links">
              <router-link to="/login" class="back-link">返回登录</router-link>
              <span class="divider">|</span>
              <router-link to="/register" class="register-link">立即注册</router-link>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { sendLoginSmsCode, checkLoginSmsCode } from '@/api/user'
import { TokenManager } from '@/utils/request'

export default {
  name: 'PhoneLoginView',
  
  setup() {
    const router = useRouter()
    
    // 登录表单数据
    const loginForm = reactive({
      mobile: '',    // 手机号
      userCode: ''   // 验证码
    })
    
    // 状态变量
    const loading = ref(false)          // 登录按钮加载状态
    const isCountDown = ref(false)      // 验证码倒计时状态
    const countDownText = ref('获取验证码') // 验证码按钮文本
    const mobileError = ref('')         // 手机号错误信息
    const codeError = ref('')           // 验证码错误信息
    const isMobileValid = ref(false)    // 手机号验证状态
    
    /**
     * 验证手机号格式
     * 检查手机号是否为空和格式是否正确
     */
    const validateMobile = () => {
      const mobileRegex = /^1[3-9]\d{9}$/
      if (!loginForm.mobile) {
        mobileError.value = '请输入手机号'
        isMobileValid.value = false
      } else if (!mobileRegex.test(loginForm.mobile)) {
        mobileError.value = '请输入正确的手机号'
        isMobileValid.value = false
      } else {
        mobileError.value = ''
        isMobileValid.value = true
      }
    }
    
    /**
     * 开始验证码倒计时
     * 设置60秒倒计时，更新按钮状态和文本
     */
    const startCountDown = () => {
      isCountDown.value = true
      let count = 60
      countDownText.value = `${count}秒后重试`
      const timer = setInterval(() => {
        count--
        countDownText.value = `${count}秒后重试`
        if (count <= 0) {
          clearInterval(timer)
          isCountDown.value = false
          countDownText.value = '获取验证码'
        }
      }, 1000)
    }
    
    /**
     * 发送验证码
     * 验证手机号并发送验证码请求
     */
    const sendCode = async () => {
      try {
        validateMobile()
        if (!isMobileValid.value) return

        const response = await sendLoginSmsCode(loginForm.mobile)
        if (response.code === 200) {
          startCountDown()
        } else {
          ElMessage.error('手机号或验证码错误')
        }
      } catch (error) {
        ElMessage.error('手机号或验证码错误')
      }
    }
    
    /**
     * 处理登录
     * 验证手机号和验证码，发送登录请求
     */
    const handleLogin = async () => {
      validateMobile()
      if (!loginForm.userCode) {
        codeError.value = '请输入验证码'
        return
      }
      if (!isMobileValid.value) return

      loading.value = true
      try {
        // 验证验证码
        const checkResponse = await checkLoginSmsCode(
          loginForm.mobile,
          loginForm.userCode
        )
        console.log('登录响应:', checkResponse) // 添加日志
        
        if (checkResponse.code === 200) {
          // 更详细地检查响应数据结构
          console.log('登录响应数据:', JSON.stringify(checkResponse.data))
          
          // 检查响应数据结构，处理特定格式
          // 在这种情况下，data字段直接包含token字符串
          const token = typeof checkResponse.data === 'string' ? checkResponse.data : 
                       (checkResponse.data && checkResponse.data.token) || checkResponse.token || ''
          
          if (!token) {
            throw new Error('登录失败：未获取到token')
          }
          
          // 从响应的根级别获取用户角色
          const userRole = checkResponse.role || 
                          (checkResponse.data && (checkResponse.data.userRole || checkResponse.data.role)) || 
                          ''
          
          // 使用TokenManager存储token
          TokenManager.setToken(token)
          
          // 保存用户角色到sessionStorage，并清除localStorage中的信息
          sessionStorage.setItem('userRole', userRole)
          localStorage.removeItem('userRole')
          
          // 检查用户角色并跳转
          const normalizedRole = String(userRole).toUpperCase()
          if (normalizedRole === 'ROOT') {
            router.push('/admin')
          } else {
            router.push('/')
          }
          
          ElMessage.success('登录成功')
        } else {
          ElMessage.error(checkResponse.message || '验证码错误')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请重试')
      } finally {
        loading.value = false
      }
    }

    return {
      loginForm,
      isCountDown,
      countDownText,
      loading,
      mobileError,
      codeError,
      isMobileValid,
      sendCode,
      handleLogin,
      validateMobile
    }
  }
}
</script>

<style scoped>
/* 复用 LoginView.vue 的基础样式 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #fff;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}

.login-box {
  display: flex;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.05);
  width: 1200px;
  min-height: 700px;
  overflow: hidden;
}

/* 左侧样式复用 LoginView.vue */
.login-left {
  flex: 1.2;
  background: #e9ecef;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.brand {
  margin-bottom: 1rem;
  position: relative;
}

.brand-image {
  width: 100%;
  max-width: 450px;
  height: 450px;
  margin-top: 0.5rem;
  margin-left: 60px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.brand-image:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.decoration-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.vase-image:hover .decoration-image {
  transform: scale(1.05);
}

.login-right {
  flex: 1;
  padding: 40px 60px;
  background: white;
}

.login-header {
  margin-bottom: 3rem;
}

.login-header h2 {
  color: #1f2937;
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
}

.login-header p {
  color: #6b7280;
  font-size: 1.1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.input-group:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.code-group {
  padding-right: 0;
}

.input-icon {
  padding: 0 1rem;
  color: #9ca3af;
}

input {
  width: 100%;
  padding: 0.75rem;
  background: transparent;
  border: none;
  font-size: 1rem;
  color: #1f2937;
  outline: none;
}

.code-btn {
  min-width: 120px;
  padding: 0.75rem 1rem;
  background: #f3f4f6;
  border: none;
  border-left: 2px solid #e5e7eb;
  color: #1890ff;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 0 10px 10px 0;
}

.code-btn:hover:not(:disabled) {
  background: #e5e7eb;
}

.code-btn:disabled {
  color: #9ca3af;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 1rem;
  background: #343a40;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #212529;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.error-message {
  color: #dc2626;
  font-size: 0.875rem;
  margin-top: 0.5rem;
  display: block;
}

.bottom-links {
  margin-top: 2rem;
  text-align: center;
}

.auth-links {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}

.divider {
  color: #e5e7eb;
}

.back-link, .register-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.back-link:hover, .register-link:hover {
  text-decoration: underline;
}

@media (max-width: 1024px) {
  .login-box {
    width: 800px;
  }
  
  .login-right {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .login-left {
    display: none;
  }
  
  .login-box {
    width: 100%;
    max-width: 500px;
  }
}
</style> 